var idTypes =[];
var insureds =[];
var relations =[];
var insuObj =[];
var objTotal={};
$(function(){	
	//初始化视图
	initView();
	//绑定button触发事件
	bindFun();
});

function initView(){
	initData();
	//点击添加 增加一行
	$("#add").click(function(){	
		addH();	
	});	
	$("#return").click(function(){	
		var queryString=getQueryString("comeUrl");
		if(queryString==2)
		{
			location.href="/pad_marketing/cover/insurance.action";
			return;
		}
		location.href="/pad_marketing/cover/cover.action";
	});
}
function initData(){
	var appBase = sessionStorage.getItem("appBase");
	delete appBase.productId;
	
	if(checkString(appBase))
	{
		alertMsg("session过期");
		setTimeout(window.location.href="/pad_marketing/login/index.action", 4000);
		return;
	}

	padMarketing.ajaxNormal('initBenefit.action', JSON.parse(appBase),
			function(result) {					
					objTotal=result;
					idTypes = objTotal.idTypes;
					insureds = objTotal.insureds;
					relations = objTotal.relations;
					insuObj = objTotal.app.bnfies;
					handleData(insuObj);
			}, function(data) {
			},false);
}
function bindFun(){
	
	$("#before").click(function(){
		var queryString=getQueryString("comeUrl");
		if(queryString==2)
		{
			location.href="/pad_marketing/cover/insurance.action";
			return;
		}
		location.href="/pad_marketing/cover/cover.action";
	});	
	$("#next").click(function(){
		
		var chArr = inputCheckTable("benefitTable");
		if(chArr[0])
		{
			return;
		}
		var arr=[];
		$("[name=cpNo]").each(function(){
			var object ={};
			object.cpNo=$(this).val();
			object.benShare=$(this).parent().parent().find("td:eq(7)").find("input").val();
			object.benSeq=$(this).parent().parent().find("td:eq(8)").find("select").val();
			if(object.benShare!=""&&object.benShare!=null){
				arr.push(object);
			}
			
		})
		if(arr.length!=0)
		{
			var result = checkNum(arr);
			if(result.flag==false){
				alertMsg(result.data);
				return;
			}
		}
		var benefitData = JSON.stringify(getTableList("benefitTable"));	
		var bnfies = getTableList("benefitTable");		
		var ob ={};
		ob.appBase = objTotal.app.appBase;
		ob.bnfies  = bnfies;
		
		padMarketing.ajaxNormal('saveBenefit.action', ob,
				function(result) {					
					  window.location.href ="/pad_marketing/main/gotoOther.action";
				}, function(data) {
				});
		
	});
	
};
//删除当前行
function deleteLine(obj){	
	alertMsg("确定删除吗？",1,function(){
		$(obj).parents('tr').remove();
		if(myScroll)
			myScroll.refresh();
	});
}
function addH(){
	var html = "";
	html+="<tr bnfyNo=''>";
	html+="<td>";
	html+='<select class="form-control" name="cpNo">';
	for(var i in insureds){
		html+='<option value="'+insureds[i].val+'">'+HtmlEncode(insureds[i].text)+'</option>';
	}
	html+='</select>';
	html+='</td>';	
	html+='<td>';
	html+='<input class="form-control" type="text" required="required" name="name" tp="1"/>';
	html+='</td>';
	html+='<td>';
	html+='<select class="form-control" name="rlToInsName" tp="2" required="required" onchange="nameSex(this)">';
	html+='<option value="">请选择</option>';
	for(var i in relations){
		html+='<option gender ="'+relations[i].gender+'" OppositeCodeSex ="'+relations[i].name+'" value ="'+relations[i].code+'">'+relations[i].name+'</option>';
	}
	html+='</select>';
	html+='</td>';
	html+='<td>';
	html+='<select class="form-control" name="idType">';	
	html+='<option value="National ID">身份证</option>';
	for(var i in idTypes){
		if(idTypes[i].val!="National ID"){
			html+='<option value="'+idTypes[i].val+'">'+idTypes[i].text+'</option>';
		}				
	}	
	html+='</select>';
	html+='</td>';
	html+='<td>';
	html+='<input class="form-control" type="text" tp="3" required="required" onchange="leadBirth(this)" onblur="checkBirth(this)" name="idNo"/>';
	html+='</td>';
	html+='<td>';		
	html+='<input class="form-control" type="text" tp="4" data-role="datebox" required="required" name="dataOfBirth"/>';
	html+='</td>';	
	html+='<td>';
	html+='<select disabled="disabled" class="form-control"  name="sexName">';				
	html+='<option value="M">男</option>';		
	html+='<option value="F">女</option>';
	html+='</select>';
	html+='</td>';
	html+='<td>';
	html+='<input class="form-control" type="number" required="required" tp="5" name="benSeq"/>';
	html+='</td>';
	html+='<td>';
	html+='<select class="form-control"  name="bnfyNo">';
	html+='<option value="1">1</option>';
	html+='<option value="2">2</option>';
	html+='<option value="3">3</option>';
	html+='</select>';
	html+='</td>';
	html+='<td class="delete" onclick=deleteLine(this)>';
	html+='<button class="btn-icon"><span class="icon icon-remove"></span></button>';
	html+='</td>';
	html+='</tr>';
    $("#benefitTable tbody").append(html);
    initDate();
    if(myScroll)
		myScroll.refresh(); 
   
}
//获取受益人表单信息
var getTableList = function(id){
	
	var list = [];
	var tb = $("#"+id+" tr:gt(0)");
	for( i=0;i<tb.length;i++){
		var obj = {};
		//受益人信息
			//缺少的
			obj.appId=tb.eq(i).attr("appId");
			obj.bnfyNo=tb.eq(i).attr("bnfyNo");
			
			
			obj.cpNo        = tb.eq(i).find('td:eq(0)').find("select").val(); //被保险人code
			obj.cpName		=tb.eq(i).find('td:eq(0)').find("select").find("option:selected").text();//被保险人姓名
			obj.name        = tb.eq(i).find('td:eq(1)').find("input").val(); //姓名
			obj.rlToInsName = tb.eq(i).find('td:eq(2)').find("select").find("option:selected").text(); //是被保险人
			obj.rlToIns = tb.eq(i).find('td:eq(2)').find("select").val(); //是被保险人		
			obj.idType	    = tb.eq(i).find('td:eq(3)').find("select").val(); //证件类型
			obj.idTypeName	=tb.eq(i).find('td:eq(3)').find("select").find("option:selected").text();
			obj.idNo        = tb.eq(i).find('td:eq(4)').find("input").val(); //证件号码
			obj.dateOfBirth = tb.eq(i).find('td:eq(5)').find("input").val(); //出生日期
			obj.sex         = tb.eq(i).find('td:eq(6)').find("select").val(); //性别
			obj.sexName		=tb.eq(i).find('td:eq(6)').find("select").find("option:selected").text();
			obj.benShare    = tb.eq(i).find('td:eq(7)').find("input").val(); //受益率
			obj.benSeq      = tb.eq(i).find('td:eq(8)').find("select").val(); //受益顺序
			if(obj.benShare!=""&&obj.benShare!=null){
				list.push(obj);
			}
	}
	
	return list;
	
}
function handleData(insuObj){
	if(insuObj.length==0){
		/*addH();*/
	}else{
		var html="";
		for(var i in insuObj ){
			var html = "";
			html+="<tr bnfyNo='"+insuObj[i].bnfyNo+"' appId='"+insuObj[i].appId+"'>";
			html+="<td>";
			html+='<select class="form-control" name="cpNo">';
			var cpNo = insuObj[i].cpNo;
			var v="";
			var t="";
			for(var j in insureds){
				if(cpNo==insureds[j].val){
					v=insureds[j].val;
					t=insureds[j].text;
				}
			}
			
			html+='<option value="'+v+'">'+HtmlEncode(t)+'</option>';

			html+='</select>';
			html+='</td>';			
			html+='<td>';
			html+='<input name="name" tp="1" required="required" class="form-control" type="text" value="'+insuObj[i].name+'"></input>';
			html+='</td>';
			html+='<td>';
			html+='<select class="form-control" tp="2" name="rlToInsName" required="required" onchange="nameSex(this)">';				
			html+='<option gender ="'+insuObj[i].sex+'" value ="'+insuObj[i].rlToIns+'">'+insuObj[i].rlToInsName+'</option>';
			html+='</select>';
			html+='</td>';
			html+='<td>';
			html+='<select name="idType" class="form-control">';				
			html+='<option value="'+insuObj[i].idType+'">'+insuObj[i].idTypeName+'</option>';		
			html+='</select>';
			html+='</td>';
			html+='<td>';
			html+='<input name="idNo" tp="3" required="required" onchange="leadBirth(this)" onblur="checkBirth(this)" class="form-control" type="text" value="'+insuObj[i].idNo+'"></input>';
			html+='</td>';
			html+='<td>';		
			html+='<input name="dateOfBirth" tp="4" required="required" class="form-control" type="text" data-role="datebox" value="'+insuObj[i].dateOfBirth+'"></input>';
			html+='</td>';	
			html+='<td>';
			html+='<select disabled="disabled"  name="sexName" class="form-control">';				
			html+='<option  value="'+insuObj[i].sex+'">'+insuObj[i].sexName+'</option>';					
			html+='</select>';
			html+='</td>';
			html+='<td>';
			html+='<input name="benShare" tp="5" required="required" class="form-control" type="number" value="'+insuObj[i].benShare+'"></input>';
			html+='</td>';
			html+='<td>';
			html+='<select name="benSeq" required="required" class="form-control">';
			html+='<option value="'+parseInt(insuObj[i].benSeq)+'">'+parseInt(insuObj[i].benSeq)+'</option>';
			html+='</select>';
			html+='</td>';
			html+='<td class="delete" onclick=deleteLine(this)>';
			html+='<button class="btn-icon"><span class="icon icon-remove"></span></button>';
			html+='</td>';
			html+='</tr>';
		    $("#benefitTable tbody").append(html);
		}
		initDate();
		init2($('[name="rlToInsName"]')); 
		init3($('[name="idType"]'));
		init4($('[name="sexName"]'));
		init5($('[name="benSeq"]'));
		if(myScroll)
			myScroll.refresh(); 
	}
	
}

function init2(obj){	
	var html="";
	for(var i in relations){
		html+='<option gender ="'+relations[i].gender+'" OppositeCodeSex ="'+relations[i].name+'" value ="'+relations[i].code+'">'+relations[i].name+'</option>';
	}
	obj.each(function(i){
		var val =$(this).val();
		$(this).html("");
		$(this).html(html);
		$(this).val(val);
	});	
}
function init3(obj){
	var html="";
	for(var i in idTypes){
		html+='<option value="'+idTypes[i].val+'">'+idTypes[i].text+'</option>';		
	}
	
	obj.each(function(i){
		var val =$(this).val();
		$(this).html("");
		$(this).html(html);
		$(this).val(val);
	});
}
function init4(obj){
	var html="";
	html+='<option value="M">男</option>';		
	html+='<option value="F">女</option>';
	obj.each(function(i){
		var val =$(this).val();
		$(this).html("");
		$(this).html(html);
		$(this).val(val);
	});
	
}
function init5(obj){
	var html="";
	for(var i=1;i<=3;i++){
		html+='<option value="'+i+'">'+i+'</option>';
	}		
	obj.each(function(i){
		var val =$(this).val();
		$(this).html("");
		$(this).html(html);
		$(this).val(val);
	});
	
}
function nameSex(obj){
	var gender = $(obj).find("option:selected").attr("gender");
	$(obj).parent().parent().find('td:eq(6)').find("select").val(gender);
}
function lookMax(arr) { 
	var max = arr[0];
	var len = arr.length; 
	for (var i = 1; i < len; i++){ 
		if (arr[i] > max) { 
		max = arr[i]; 
		} 
	} 
	return max;
}
function lookMin(arr) {
	var min = arr[0];
	var len = arr.length;
	for (var i = 1; i < len; i++){ 
	if (arr[i] < min){ 
	min = arr[i]; 
	}
   }
	return min;
}
function checkNum(arr){
	var result={};
	var num=[];
	for(var i in arr){
		
		num.push(parseInt(arr[i].benSeq));
	}
	var max=lookMax(num);
	var min=lookMin(num);
	var cha=max-min;
	if(min!=1)
	{
		result.flag=false;
		result.data="各被保险人的受益顺序应连续";
		return result;
		
	}
	if(cha!=1&&cha!=0){
		var int =num.indexOf(2);
		if(int==-1){
			result.flag=false;
			result.data="各被保险人的受益顺序应连续";
			return result;
		}
	}
	var ar1=[];
	var ar2=[];
	var ar3=[];
	for(var i in arr)
	{
		if(arr[i].benSeq=="1"){
			ar1.push(parseInt(arr[i].benShare));
		}else if(arr[i].benSeq=="2"){
			ar2.push(parseInt(arr[i].benShare));
		}else if(arr[i].benSeq=="3"){
			ar3.push(parseInt(arr[i].benShare));
		}
	}
	var total=0;
	if(ar1.length!=0){
		for(var i in ar1){
			total+=ar1[i];
			
			
		}
		if(total!=100)
		{
			result.flag=false;
			result.data="各被保险人的各受益顺序的合计受益率应为100%";
			return result;
		}
	}
	
	
	var tota=0;
	if(ar2.length!=0)
	{
		for(var i in ar2){
			tota+=ar2[i];
			
			
		}
		if(tota!=100)
		{
			result.flag=false;
			result.data="各被保险人的各受益顺序的合计受益率应为100%";
			return result;
		}
	}
	
	
	var tot=0;
	if(ar3.length!=0)
	{
		for(var i in ar3){
			tot+=ar3[i];
			
			
		}
		if(tot!=100)
		{
			result.flag=false;
			result.data="各被保险人的各受益顺序的合计受益率应为100%";
			return result;
		}
	}
	result.flag=true;
	return result;
}

function inputCheckTable(benefitTable){
	var flag = false;	
	$("#"+benefitTable+" input[required='required'],select[required='required']").each(
		function(index,me,arg){
			var v = $(me).val();			
			if(v=="" || v==null){
				//添加全行校验 全行如果为空 不报错
				if(checkAllEmpty($(me).parent().parent())){
					flag = true;
					alertMsg("请填写"+speak($(me).attr("tp")),0,function(){
						$(me).focus();
					});				
					return false;
				}else{
					return true;
				}
				
			}
	});
	
	if(flag) return [flag];
	return [flag];
}

function initDate(){
	var currYear = (new Date()).getFullYear();
	//日期
	var opt = {
        preset: 'date', //日期
        theme: 'android-ics light', //皮肤样式
        display: 'bottom', //显示方式 
        mode: 'scroller', //日期选择模式
        lang: 'zh',
        dateFormat: 'yy-mm-dd', // 日期格式
        setText: '确定', //确认按钮名称
        cancelText: '取消',//取消按钮名籍我
        dateOrder: 'yymmdd', //面板中日期排列格式
        dayText: '', monthText: '', yearText: '', //面板中年月日文字
        startYear: currYear-100,
        endYear: currYear  //结束年份
	};
	if($('input[data-role=datebox]').mobiscroll)
		$('input[data-role=datebox]').mobiscroll(opt);
}
function leadBirth(me){
	var re = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
	var idType = $(me).parent().parent().find("td:eq(3)").find("select").val();
	var idCode = $(me).val();
	if(idType=="National ID"){
		if(!re.test(idCode)){
			return;
		}
		var idOfbirth = idCode.substr(6,8);
		var numO = idOfbirth.substr(0,4);
		var numT = idOfbirth.substr(4,2);
		var numH = idOfbirth.substr(6,4);
		var num = numO+'-'+numT+'-'+numH;
		$(me).parent().parent().find("td:eq(5)").find("input").val(num);
	}
}
function checkBirth(){
	var re = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
	var idType = $(me).parent().parent().find("td:eq(3)").find("select").val();
	var idCode = $(me).val();
	if(idType=="National ID"){
		if(!re.test(idCode)){
			alertMsg("请正确填写身份证号码");
			return;
		}
	}
}
function checkAllEmpty(obj){
	var flag = false;
	$(obj).find("select[required='required']").each(function(index,me,arg){
		var v = $(me).val();
		if(v){
			flag=true;
			return false;
		}
	});
	
	$(obj).find("input[required='required']").each(function(index,me,arg){
		var v = $(me).val();
		if(v){
			flag=true;
			return false;
		}
	});
	if(flag) return true;
	return false;
}
function speak(flag){
	switch(flag){
	case "1":return "受益人的姓名";
	break;
	case "2":return "与被保险人的关系";
	break;
	case "3":return "证件号码";
	break;
	case "4":return "出生日期";
	break;
	case "5":return "受益率";
	break;
	default: return "完整数据";
		
}
}